import Canvas from '../../store/canvas/canvas'
import { generateUUID } from '../../utils'
import { dispatcher } from '../core/Dispatcher'
import { currentTime } from '../core/SimulationClock'
import { messageTransfer } from '../messaging/MessageTransfer'
import BaseStation from './BaseStation'
import Worker from './Worker'

class workerPool {
  id: string
  name: string
  x: number
  y: number
  //总人数
  workerNum: number
  //空闲人数
  freeWorkerNum: number
  //工人速度
  workerSpeed: number
  //维修时间
  maintenanceTime: number
  // 设备映射表
  deviceMap: { id: string; name: string }[]
  //待办事项
  todoList: { type: 'clean' | 'maintenance'; station: BaseStation }[] = []

  constructor(
    id: string,
    name: string,
    x: number,
    y: number,
    workerNum: number,
    workerSpeed: number,
    maintenanceTime: number,
    deviceMap: { id: string; name: string }[]
  ) {
    this.id = id
    this.name = name
    this.x = x
    this.y = y
    this.workerNum = workerNum
    this.freeWorkerNum = workerNum
    this.workerSpeed = workerSpeed
    this.maintenanceTime = maintenanceTime
    this.deviceMap = deviceMap
  }

  /**
   * 遍历所有关联设备，然后判断哪些设备需要人协助
   */
  initManualStation() {
    this.deviceMap.forEach((device) => {
      const nodes = Canvas.getNodes('id', device.id)
      if (nodes.length === 0) return
      const node = nodes[0]
      if (node.simData.process?.personAssist && this.freeWorkerNum > 0) {
        const targetNode = Array.from(dispatcher.idleStations).find((item) => item.id === node.id)
        if (!targetNode) return
        this.changeWorkerNum('-1')
        //此设备需要工人协助
        const worker = new Worker(
          generateUUID(),
          this.x,
          this.y,
          targetNode,
          this,
          'assist',
          this.workerSpeed,
          this.maintenanceTime
        )
        messageTransfer('workerPool', 'generate', {
          targetId: this.id,
          workerId: worker.id
        })
        //执行任务
        worker.executeTask()
      }
    })
  }

  //判断某台设备是否在自己的映射表中
  isDeviceInMap(deviceId: string) {
    return this.deviceMap.some((device) => device.id === deviceId)
  }

  //任务接收器
  receiveTask(type: 'clean' | 'maintenance', device: BaseStation) {
    //如果该设备已经在todolist里面，则不重复添加
    if (this.todoList.some((item) => item.station.id === device.id)) return
    this.todoList.push({
      type,
      station: device
    })
    this.executeTask()
  }

  //执行任务
  executeTask() {
    if (this.todoList.length === 0) return
    if (this.freeWorkerNum < 1) return
    while (this.todoList.length > 0) {
      //拿到todoList的第一个元素
      const item = this.todoList.shift()
      if (!item) break
      dispatcher.clearNegativeStatus(item.station)
      if (item.type === 'clean') {
        console.log(`[${currentTime}] 🚿 ${this.name} 开始清理 ${item.station.name}`)
        this.startCleanStation(item.station)
      } else if (item.type === 'maintenance') {
        console.log(
          `[${currentTime}] 🔧 ${this.name} 开始维修 ${item.station.name} 预计需要时间 ${this.maintenanceTime} }`
        )
        this.startMaintenanceStation(item.station)
      }
    }
  }

  /**
   * 当有设备需要清洁时，比如产品发生了不良率
   */
  startCleanStation(device: BaseStation) {
    if (this.freeWorkerNum < 1) return
    this.changeWorkerNum('-1')
    const worker = new Worker(
      generateUUID(),
      this.x,
      this.y,
      device,
      this,
      'clean',
      this.workerSpeed,
      this.maintenanceTime
    )
    messageTransfer('workerPool', 'generate', {
      targetId: this.id,
      workerId: worker.id
    })
    //执行任务
    worker.executeTask()
  }

  /**
   * 当有设备需要维修时，比如设备故障
   */
  startMaintenanceStation(device: BaseStation) {
    if (this.freeWorkerNum < 1) return
    this.changeWorkerNum('-1')
    const worker = new Worker(
      generateUUID(),
      this.x,
      this.y,
      device,
      this,
      'maintenance',
      this.workerSpeed,
      this.maintenanceTime
    )
    messageTransfer('workerPool', 'generate', {
      targetId: this.id,
      workerId: worker.id
    })
    //执行任务
    worker.executeTask()
  }

  //有人员进行了返程
  returnHome(workerId: string) {
    messageTransfer('workerPool', 'recycle', {
      targetId: workerId
    })
    this.changeWorkerNum('+1')

    //查看是否有待办事项
    this.executeTask()
  }

  private changeWorkerNum(mark: '-1' | '+1') {
    if (mark === '+1') {
      this.freeWorkerNum++
    } else {
      this.freeWorkerNum--
    }

    messageTransfer('style', null, {
      targetId: this.id,
      style: {
        quantity: this.freeWorkerNum
      }
    })
  }
}

export default workerPool
